#include "networkmanager.h"
#include "configmanager.h"
#include "configdef.h"

#include <QTimer>
#include <QEventLoop>
#include <QSslConfiguration>
#include <QSslSocket>
#include <QDebug>
#include <QUrlQuery>

// 静态成员初始化
NetworkManager* NetworkManager::m_instance = nullptr;
QMutex NetworkManager::m_instanceMutex;

NetworkManager::NetworkManager(QObject *parent)
 	: QObject(parent)
{
	m_nam = new QNetworkAccessManager(this);
	initSSLConfig();		// Qt默认访问https请求有点问题 要初始化一下
}

NetworkManager *NetworkManager::getInstance(QObject *parent)
{
	if (!m_instance) {
        QMutexLocker locker(&m_instanceMutex);
        if (!m_instance) {
            m_instance = new NetworkManager(parent);
        }
    }
    return m_instance;
}

NetworkManager::~NetworkManager()
{
	// 析构的时候要回收
	if (m_nam) {
		m_nam->deleteLater();
		m_nam = nullptr;
	}
	m_instance = nullptr;
}

// 发送POST请求，返回reply，需上层自行管理
QNetworkReply *NetworkManager::sendPostRequest(const QString &urlStr, const QMap<QString, QString> &params)
{
	QUrl url(urlStr);
	QNetworkRequest request(url);
	// 设置请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded; charset=utf-8");
    request.setHeader(QNetworkRequest::UserAgentHeader, "scSmartInput/1.0");  // 需求3.2

	QUrlQuery query;
    for (auto it = params.begin(); it != params.end(); ++it) {
        query.addQueryItem(it.key(), it.value());
    }
    QByteArray postData = query.toString().toUtf8();

	QNetworkReply* reply = m_nam->post(request, postData);
	// 设置超时
    QTimer::singleShot(m_timeout, reply, [reply]() {
        if (!reply->isFinished()) {
            reply->abort();
            qWarning() << "[NetworkManager] 请求超时：" << reply->url().toString();
        }
    });

    return reply;
}

///////////////////////////////////////////////////////////
// tools
void NetworkManager::initSSLConfig()
{
	// 配置SSL：解决Qt默认不信任部分HTTPS证书的问题（生产环境可改为加载自定义证书）
	QSslConfiguration sslConf = QSslConfiguration::defaultConfiguration();
	sslConf.setPeerVerifyMode(QSslSocket::VerifyNone); // 简化配置，避免证书校验失败
    sslConf.setProtocol(QSsl::TlsV1_2OrLater);        // 强制使用TLS 1.2+，保证安全性
    QSslConfiguration::setDefaultConfiguration(sslConf);
    qInfo() << "[NetworkManager] SSL配置初始化完成";
}
